<template>
	<view class="wrapper">
    <view class="edit-line" v-if="list.length > 0">
      <view
          class="edit"
          :class="{'active': edit}"
          @click="edit = !edit"
      >{{ edit ? '完成': '编辑' }}</view>
    </view>
    <view class="tip" v-if="showTip">
      <text class="warn"> 注意: </text>
      <text class="text"> 不同分区商品不能同时下单 </text>
    </view>
    <!-- 没有商品 -->
    <view class="nothing" v-if="list.length === 0">
      <view>您还没有添加任何商品到购物车</view>
      <view class="look" @click="goHome">去逛逛</view>
    </view>
    <!-- 推荐 -->
    <Like v-if="list.length === 0" />
    <!-- 购物车 -->
    <view class="cart" :class="{'text' : showTip}" v-if="list.length > 0">
      <view class="list">
        <view class="item" v-for="(item, index) in list" :key="index">
          <view class="area">[ {{ item.areaName }} ]</view>
          <view class="content" v-if="item.product">
            <view class="checked">
              <u-checkbox-group @change="checkedItem(item)">
                <u-checkbox :checked="item.selected" :activeColor="activeColor" iconSize="16px" size="20px" shape="circle" label="选择" labelSize="0"></u-checkbox>
              </u-checkbox-group>
            </view>
            <view class="image" @click="goProduct(item)">
              <u--image class="img" lazy-load width="100rpx" height="100rpx" :fade="true" duration="450" :src="baseUrl + item.sku.image.thumbnail_path" v-if="item.sku && item.sku.image"></u--image>
              <u--image class="img" lazy-load width="100rpx" height="100rpx" :fade="true" duration="450" :src="baseUrl + item.product.mainImage.thumbnail_path" v-else-if="item.product.mainImage"></u--image>
            </view>
            <view class="desc">
              <view class="title">{{ item.product.title }}</view>
              <view class="sku" v-if="item.selected_sku_text">{{ JSON.parse(item.selected_sku_text).join(', ') }}</view>
              <view class="price">￥{{ item.price }}</view>
              <view class="num">
                <num :item="item"
                     @addQuantity="addQuantity"
                     @subQuantity="subQuantity"
                     @changeQuantity="changeQuantity" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="footer">
        <view class="all-checked">
          <view class="icon">
            <u-checkbox-group @change="checkedAll">
              <u-checkbox :checked="allSelected" :activeColor="activeColor" iconSize="16px" size="20px" shape="circle" label="全选" labelSize="0"></u-checkbox>
            </u-checkbox-group>
          </view>
          <view class="sum">已选({{totalQuantity}})</view>
        </view>
        <view class="right">
          <view class="price">
            <text v-if="!edit">￥{{ totalPrice }}</text>
          </view>
          <view class="btn" v-if="!edit" @click="goOrder">去结算</view>
          <view class="btn delete" v-if="edit" @click="deleteCart">删除</view>
          <view class="btn clear" v-if="edit" @click="clearCart">清空</view>
        </view>
      </view>
    </view>
    <v-tab :selected="'/pages/cart/index'" />
  </view>
</template>

<script>
import Tab from '../../components/tab'
import color from '@/config/color.js'

import config from '../../config/config'
import base64 from '../../util/base64'
import Cart from '../../api/cart'
import Like from '../../components/like/index'
import Num from './components/Num'
import List from '../../components/list'
const cartModel = new Cart()
	export default {
    components: {
      Like,
      Num,
      'v-tab': Tab
    },
    computed: {
      // 判断多个区选中
      showTip() {
        const list = this.list.filter(x => x.selected).map(x => x.areaName)
        return new Set([...list]).size > 1
      },
      // 全选
      allSelected() {
        return this.list.every(x => x.selected)
      },
      // 总数量
      totalQuantity() {
        const selected = this.list.filter(x => x.selected)
        let total = 0
        selected.forEach(x => {
          total += +x.quantity
        })
        return +total
      },
      // 总价
      totalPrice() {
        const selected = this.list.filter(x => x.selected)
        let price = 0
        selected.forEach(x => {
          // price += +x.quantity * x.product.price
          price += +x.quantity * x.price
        })
        return +price.toFixed(2)
      }
    },
    watch: {
      // 购物车数量
      list: {
        deep: true,
        handler(v) {
          this.$store.dispatch('Cart/set_change_list', v).then(() => {
            if (this.$store.getters['Cart/showTotal'] > 0) {
              // uni.setTabBarBadge({
              //   index: 2,
              //   text: this.$store.getters['Cart/showTotal']
              // })
            } else {
              // uni.removeTabBarBadge({
              //   index: 2,
              // })
            }
          })
        }
      }
    },
		data() {
			return {
			  list: [],
        edit: false,
        baseUrl: config.baseUrl,
        activeColor: color.main_color
			}
		},
    onLoad() {
      uni.hideTabBar({
        animation: false,
        success: () => {
        },
        fail: () => {
        }
      })
    },
		onShow() {
      this.getList()
		},
		methods: {
      // 数量操作
      addQuantity(item) {
        item.quantity = item.quantity + 1
        cartModel.increment({ ...item }).then(() => {
          this.list.forEach(x => {
            if (x.id === item.id) {
              x.quantity = item.quantity
              x.selected = true
            }
          })
        })
      },
      subQuantity(item) {
        item.quantity = item.quantity - 1
        item.selected = true
        cartModel.decrement({ ...item }).then(() => {
          // 小程序中需要这样写,才能改变值
          this.list.forEach(x => {
            if (x.id === item.id) {
              // this.$set(x, 'quantity', item.quantity)
              x.quantity = item.quantity
              x.selected = true
            }
          })
        })
      },
      changeQuantity(item) {
        cartModel.changeNum({ ...item }).then(() => {
          this.list.forEach(x => {
            if (x.id === item.id) {
              x.quantity = +item.quantity
              x.selected = true
            }
          })
        })
      },
      goHome() {
		    uni.switchTab({
          url: '/pages/index/index'
        })
      },
      getList() {
		    cartModel.list().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.list = data
          // console.log(this.list)
          this.list.forEach(x => {
            this.$set(x, 'selected', +x.selected !== 0)
            const area = (x.product.area && x.product.area[0] && x.product.area[0].name && x.product.area[0].name.name) || ''
            this.$set(x, 'areaName', area)
          })
        })
      },
      goProduct(item) {
        uni.navigateTo({
          url: `/sub_product/detail/index?id=${item.product.id}`
        })
      },
      // 单独选择
      checkedItem(item) {
		    this.list.forEach(x => {
		      if (x.id === item.id) {
		        const selected = !x.selected
            this.$set(x, 'selected', selected)
            cartModel.itemSelected({ id: item.id, selected }).then(() => {})
          }
        })
      },
      // 全选
      checkedAll() {
		    const v = !this.allSelected
        this.list.forEach(x => {
          this.$set(x, 'selected', v)
        })
        cartModel.allSelected({ selected: v }).then(() => {})
      },
      deleteCart() {
        cartModel.remove().then(() => {
          this.edit = false
          this.list = this.list.filter(x => x.selected === false)
          uni.showToast({
            title: '删除成功',
            icon: 'none',
            duration: 500
          })
        })
      },
      clearCart() {
        cartModel.clear().then(() => {
          this.edit = false
          this.list = []
          uni.showToast({
            title: '清空成功',
            icon: 'none',
            duration: 500
          })
        })
      },
      goOrder() {
        if (this.showTip) {
          return uni.showToast({
            title: '不同分区商品不能同时下单',
            icon: 'none',
            duration: 1000
          })
        }
        // 跳转
        // const params = JSON.stringify({ cart: true })
        const params = base64.encodeUrl({ cart: true })
        uni.navigateTo({
          url: `/sub_main/order/index?params=${params}`
        })
      }
		}
	}
</script>

<style lang="scss" scoped>
.wrapper {
  font-size: 24rpx;
  background: $background_color;
  padding-bottom: 60px;
  .nothing {
    display: flex;
    flex-direction: column;
    height: 300rpx;
    justify-content: space-around;
    align-items: center;
    letter-spacing: 3rpx;
    .look {
      background: $main_color;
      display: inline-block;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      color: white;
    }
  }
  .edit-line {
    position: fixed;
    left: 0px;
    top: 0px;
    /*  #ifdef  H5  */
    top: 43px;
    /*  #endif  */
    z-index: 99999;
    background: $background_color;
    width: 100%;
    .edit {
      margin-left: 10px;
      width: 60px;
      text-align: center;
      height: 25px;
      line-height: 25px;
      background: $main_color;
      color: white;
      border-radius: 5px;
      font-size: 24rpx;
      &.active {
        //color: red;
        color: #ffffff;
        font-weight: 700;
      }
    }
  }
  .tip {
    height: 30px;
    line-height: 30px;
    background: #ccc;
    color: red;
    font-size: 24rpx;
    letter-spacing: 3rpx;
    position: fixed;
    width: 100%;
    z-index: 10;
    left: 0;
    top: 25px;
    /*  #ifdef  H5  */
    top: 68px;
    /*  #endif  */
    .warn {
      font-weight: 700;
      margin-left: 10px;
    }
    .text {
      margin-left: 10px;
    }
  }
  .cart {
    //background: black;
    padding-top: 30px;
    //background: black;
    &.text {
      padding-top: 65px;
    }
    .footer {
      height: 40px;
      line-height: 40px;
      //background: white;
      position: fixed;
      z-index: 100;
      bottom: 55px;
      /*  #ifdef  H5  */
      bottom: 105px;
      /*  #endif  */
      left: 0;
      width: 100%;
      display: flex;
      background: white;
      justify-content: space-between;
      .all-checked {
        //background: red;
        width: 300rpx;
        padding-left: 30rpx;
        display: flex;
        align-items: center;
      }
      .right {
        flex: 1;
        display: flex;
        .btn {
          width: 140rpx;
          font-size: 28rpx;
          background: $main_color;
          text-align: center;
          color: white;
          &.delete {
            color: white;
            background: red;
          }
          &.clear {
            color: white;
            background: black;
          }
        }
        .price {
          flex: 1;
          text-align: right;
          padding-right: 20rpx;
          color: red;
          font-size: 32rpx;
          font-weight: 700;
        }
      }
    }
    .list {
      min-height: 600px;
      //background: red;
      padding: 0 20rpx;
      .item {
        margin-bottom: 10px;
        background: white;
        border-radius: 5px;
        padding: 10px;
        display: flex;
        flex-direction: column;
        .area {
          height: 25px;
          line-height: 25px;
          //background: blue;
          font-weight: 700;
          color: $main_color;
        }
        .content {
          display: flex;
          .checked {
            width: 80rpx;
            box-sizing: border-box;
            padding-top: 20px;
            padding-left: 15px;
            //background: red;
          }
          .image {
            width: 160rpx;
            //background: black;
            image, .img {
              width: 100rpx;
              height: 100rpx;
              display: block;
              margin: auto;
            }
          }
          .desc {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            //background: red;
            view {
              height: 20px;
              &.price {
                color: red;
                font-weight: 700;
              }
              &.title {
                font-weight: 700;
                overflow: hidden;
                //height: 30px;
              }
              &.sku {
                overflow: hidden;
              }
              &.num {
                height: 25px;
                margin-top: -10px;
                //display: flex;
                //justify-content: end;
              }
            }
          }
        }
      }
    }
  }
}
</style>
